import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity, Image, FlatList
} from "react-native";
import { GLOBAL } from '../../../../config/global';
import StorageHelper from '../../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../../config/storage';
import { style } from '../../../../theme/style';
import { Common } from '../../../../component/common/Common';
import { OyNotItem } from '../component/OyNotItem';
import { OyTypeItem } from '../component/OyTypeItem';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import CreditService from '../_common/service.js';
import { RangTime } from '../../../../component/common/RangTime.js';
import { SearchInput } from '../../../../component/SearchInput.js';
import MethodUtil from '../../../../utils/MethodUtil';
import * as Animatable from 'react-native-animatable';
import { NewAccount } from '../../../../components/common/newAccount';
import { SlideSelect } from '../../../../components/common/slideSelect';
const scale = GLOBAL.SCALE;

export class OccupyListPage extends Component {
	static navigationOptions = ({ navigation }) => {
		return {
			headerTitle: '授信占用未核记录',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center',
			}
		}
	};

	constructor(props) {
		super(props);
		const { choice } = props.navigation.state.params || {};
		this.state = {
			selectVal: null,
			modelData: [[  //关闭未核、逾期未核、未逾期未核
				{ bizType: 'all_p', title: '全部' },
				{ bizType: 'notOverdue_p', title: '未逾期' },
				{ bizType: 'overdue_p', title: '已逾期' }
			], [  //关闭未核、逾期未核、未逾期未核
				{ bizType: 'all_s', title: '全部' },
				{ bizType: 'notOverdue_s', title: '未逾期' },
				{ bizType: 'overdue_s', title: '已逾期' },
				{ bizType: 'delay_s', title: '已延期' },
				{ bizType: 'close_s', title: '已关闭' }
			]],
			modeIndex: 0,
			modalVisible: false,
			tabIndex: 0,

			timeModel: false, //日期弹框显示/隐藏
			listData: [], // 列表数据
			_isLoad: false,  // 下拉涮新的 图标
			loaded: 'loading', // 加载状态
			closeLoader: false,
			headData: {},   // 头部数据
			alertShow: false,
			options: [],
			choice: choice || {}
		}
		this.sendData = {
			startDate: null,  // 开始时间
			endDate: null, //介绍时间
			pageNo: 1,  // 页码
			searchKey: null, // 搜索词
			orderType: 'P', // 类型
			checkType: 'all'
		}
		this.totalPage = 0; // 存总页码
		this.anmateOnoff = true;
	}

	async	componentWillMount () {
		await this.getSorage();
		await this._getHeadData();
		await this._getData(true);
	}

	//获取业务组织
	async	getSorage () {
		const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
		const userInfo = JSON.parse(userInfoJson);
		this.setState({
			options: userInfo.corpInfoTOs || [],
			choice: this.state.choice.corpId ? this.state.choice : userInfo.corpInfoTOs[0]
		})
	}


	//刷新
	_getData = async (refreshOff) => {
		let { tabIndex, choice } = this.state;

		if (refreshOff) {
			this.setState({
				_isLoad: true,
				loaded: 'loading'
			});
		}
		let responseData = null
		if (tabIndex == 2) {
			responseData = await CreditService.oyNotList({ searchKey: this.sendData.searchKey, corpId: choice.corpId });
		} else {
			this.sendData.corpId = choice.corpId;
			responseData = await CreditService.oyList(this.sendData);
		}
		this.totalPage = responseData.totalPage;
		if (refreshOff) {  // 下拉刷新
			if (responseData && responseData.rows.length) {
				this.totalPage = responseData.totalPage;
				this.setState({
					loaded: 'data',  // 初始化一次
					_isLoad: false,
					listData: responseData.rows,
				});
			} else {  //没数据
				this.setState({
					loaded: 'empty',
					_isLoad: false,
					listData: responseData.rows,
				});
			}
		} else { // 上拉加载
			this.setState({
				listData: this.state.listData.concat(responseData.rows),
			});
		}
	}

	//头部数据
	_getHeadData = async () => {
		let { tabIndex, choice } = this.state;

		if (tabIndex == 2) {
			responseData = await CreditService.oyListHeadNot({ searchKey: this.sendData.searchKey, corpId: choice.corpId });
		} else {
			this.sendData.corpId = choice.corpId;
			responseData = await CreditService.oyListHead(this.sendData);
		}

		if (responseData) {
			this.setState({
				headData: responseData
			})
		}
	}

	// select 点击
	_itemFn = (sendObj) => {
		this._showVisible();
		this.setState({
			modeIndex: sendObj.index,
			selectVal: sendObj.item.title
		}, () => {
			this.sendData.pageNo = 1;
			this.anmateOnoff = true;
			this.handleViewRef.zoomIn(800);
			this.handleViewSildeRef.arrowDown(800);
			this.sendData.checkType = sendObj.item.bizType;
			this._getHeadData();
			this._getData(true);
		});
	}

	//点击显示隐藏
	_showVisible = () => {
		if (this.state.modalVisible) {
			this.setState({
				modalVisible: false
			})
		} else {
			this.setState({
				modalVisible: true
			})
		}
	}


	// 时间选择完成 回调
	_resultCall = (resultData) => {
		this.sendData.pageNo = 1;
		this.sendData.startDate = resultData.startTime;
		this.sendData.endDate = resultData.endTime;
		this.setState({
			timeModel: false
		}, () => {
			this._getHeadData();
			this._getData(true);
		})
	}


	//点击列表跳转
	_listPressFn = (data) => {
		this.props.navigation.navigate('OccupyDetailsPage', { 'data': data, choice: this.state.choice })
	}

	//返回一条列表View
	_renderItemView = (customer) => {
		let { tabIndex, choice } = this.state;
		return tabIndex > 1 ? <OyNotItem data={customer.item} navigationData={this.props.navigation} choice={choice} /> : <OyTypeItem data={customer.item} listPressFn={this._listPressFn} />
	}

	// 下拉更新函数
	_isLoadRefresh = () => {
		this.sendData.pageNo = 1;
		this._getHeadData();
		this._getData(true);
	}

	// 上拉更新函数
	_onEndReached = () => {
		if (this.sendData.pageNo < this.totalPage) {
			this.sendData.pageNo++;
			this._getHeadData();
			this._getData();
		}
	}

	// tab切换
	_tabFn = (tabIndex) => {
		let { modelData } = this.state;
		this.sendData.pageNo = 1;
		this.anmateOnoff = true;
		this.handleViewRef.zoomIn(800);
		this.handleViewSildeRef.arrowDown(800);
		this.setState({
			tabIndex
		}, () => {
			this.sendData.orderType = (tabIndex == 0 ? 'P' : 'S');
			if (tabIndex == 2) {
				this.sendData.checkType = null;
				this._getHeadData();
				this._getData(true);
			} else {
				this.setState({
					modeIndex: tabIndex,
					selectVal: modelData[tabIndex][0].title
				}, () => {
					this.sendData.checkType = modelData[tabIndex][0].bizType;
					this._getHeadData();
					this._getData(true);
				});
			}
		})
	}

	// 垂直滚动距离
	_scollFn = (eventObj) => {
		let offsetY = eventObj.nativeEvent.contentOffset.y;//垂直滚动距离 
		if (offsetY > 200 && this.anmateOnoff) {
			this.anmateOnoff = false;
			this.handleViewRef.zoomOut(800).then(endState => { });
			this.handleViewSildeRef.arrowUp(800);
		} else if (offsetY <= 200 && !this.anmateOnoff) {
			this.anmateOnoff = true;
			this.handleViewRef.zoomIn(800).then(endState => { });
			this.handleViewSildeRef.arrowDown(800);
		}
	}
	_handleViewRef = ref => this.handleViewRef = ref;
	_handleViewSildeRef = ref => this.handleViewSildeRef = ref;
	render () {
		const searchLeft = require('../../../../imgs/customer/searchLeft.png');
		let { modeIndex, modelData, modalVisible, tabIndex, selectVal, timeModel, listData, _isLoad, loaded, closeLoader,
			headData, alertShow, choice, options } = this.state;
		let { startDate, endDate } = this.sendData;
		return (
			<View style={styles.container}>
				{options.length > 1 ? <NewAccount fn={(val) => { this.setState({ alertShow: val }) }} choice={choice.corpName || ''} /> : null}
				<View style={[styles.headBox]}>
					<View style={styles.outSearch}>
						<View style={styles.nerSearch}>
							<SearchInput
								placeholder={'请输入企业名称/订单号'}
								inputLeftIcon={searchLeft}
								setKeyWord={(txt) => { this.sendData.searchKey = txt; }}
								onSubmitEditing={(txt) => { this._getHeadData(); this._getData(true); }}
								inputViewStyle={styles.searchStyle}
								inputStyle={{ color: '#fff' }}
								inputLeftIconStyle={styles.searchLeftIconStyle}
								placeholderTextColor={'#fff'}
								onBlurFn={() => { if (this.sendData.searchKey == '') { this._getHeadData(); this._getData(true); } }}
							/>
						</View>
					</View>
					<View style={styles.headTab}>
						<TouchableOpacity style={tabIndex == 0 ? styles.tabActive : null} onPress={() => { this._tabFn(0) }}><Text style={[styles.tabText, tabIndex == 0 ? styles.tabTextActive : null]}>采购</Text></TouchableOpacity>
						<TouchableOpacity style={tabIndex == 1 ? styles.tabActive : null} onPress={() => { this._tabFn(1) }}><Text style={[styles.tabText, tabIndex == 1 ? styles.tabTextActive : null]}>销售</Text></TouchableOpacity>
						<TouchableOpacity style={tabIndex == 2 ? styles.tabActive : null} onPress={() => { this._tabFn(2) }}><Text style={[styles.tabText, tabIndex == 2 ? styles.tabTextActive : null]}>未核统计</Text></TouchableOpacity>
					</View>
					<Animatable.View style={styles.showBoxOut} ref={this._handleViewRef}>
						<View style={styles.showBox}>
							<View style={styles.showBoxItem}>
								<Text style={styles.showTitle}>未核总额（元）</Text>
								<Text style={styles.showText}>¥{MethodUtil.toThousands(headData.totalAmount, 2) || '-'}</Text>
							</View>
							<View style={styles.showBoxItem}>
								<Text style={styles.showTitle}>未核订单（笔）</Text>
								<Text style={styles.showText}>{headData.orderNum}</Text>
							</View>
							{
								tabIndex > 1 ? (<View style={styles.showBoxItem}>
									<Text style={styles.showTitle}>未核企业（家）</Text>
									<Text style={styles.showText}>{headData.companyNum}</Text>
								</View>) : null
							}
						</View>
					</Animatable.View>
				</View>
				<Animatable.View ref={this._handleViewSildeRef} style={styles.listBoxOut}>

					{
						tabIndex == 2 ? (<View style={{ height: 20 * scale }}></View>) : (<View style={styles.listScreen}>
							<TouchableOpacity onPress={this._showVisible} style={styles.flexRow}>
								<Text style={styles.allBtn}>{selectVal || '全部'}</Text>
								<Image source={require('../../../../imgs/select.png')} />
							</TouchableOpacity>
							<TouchableOpacity style={styles.dateSelect}>
								<View style={styles.timeRight}>
									<Text style={styles.timeTitle}>到期日</Text>
									<Text style={styles.timeValue} onPress={() => { this.setState({ timeModel: true }) }}>{startDate || '开始时间'}/{endDate || '结束时间'}</Text>
								</View>
								<Image source={require('../../../../imgs/time.png')} style={{ width: 14 * scale, height: 16 * scale }} ></Image>
							</TouchableOpacity>
						</View>)}



					{
						loaded == 'data' ? (<FlatList
							data={listData}
							extraData={this.state}
							renderItem={this._renderItemView}
							refreshing={_isLoad}
							onRefresh={() => { this._isLoadRefresh() }}
							onEndReachedThreshold={0.5}
							onEndReached={() => { this._onEndReached() }}
							onScroll={(event) => {
								this._scollFn(event);
							}}
						/>) : (<PageStatusIndex status={loaded} emptyText={'暂无记录'} emptyImgSource={require('../../../../imgs/global/messageEmpty.png')} />)
					}

				</Animatable.View>
				{timeModel ? <RangTime isVisible={true} startTime={startDate} endTime={endDate} resultCall={this._resultCall} closeCall={() => { this.setState({ timeModel: false }) }} /> : null}
				{modalVisible && tabIndex != 2 ? <Common styleOut={[styles.modelOut, this.anmateOnoff ? null : styles.modelOutDowm]} data={modelData[tabIndex]} itemFn={this._itemFn} imgIndex={modeIndex} allClick={this._showVisible} type="selectModal" /> : null}
				{
					closeLoader ? (<View style={{ height: '100%', width: '100%', position: 'absolute', left: 0, top: 0, }}>
						<PageStatusIndex status={'loading'} />
					</View>) : null
				}

				<SlideSelect alertShow={alertShow} options={options}
					select={(val) => {
						this.setState({ choice: val || options[0], alertShow: false }, () => {
							this._isLoadRefresh();
						})
					}}
					unselect={() => {
						this.setState({ alertShow: false })
					}} />
			</View>
		)
	}
}

Animatable.initializeRegistryWithDefinitions({
	arrowUp: {
		from: {
			marginTop: 0
		},
		to: {
			marginTop: -90 * scale
		},
	},
	arrowDown: {
		from: {
			marginTop: -90 * scale
		},
		to: {
			marginTop: 0
		},
	}
});
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray
	},
	flexRow: {
		flexDirection: 'row',
		alignItems: 'center',
	},
	listScreen: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
		height: 60 * scale,
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,
	},
	headBox: {
		backgroundColor: style.color.themeColor,
		height: 180 * scale,
		width: '100%',
	},
	smallHeadBox: {
		height: 95 * scale,
	},
	outSearch: {
		height: 36 * scale,
		width: '100%',
		flexDirection: 'row',
		justifyContent: 'center'
	},
	nerSearch: {
		height: 36 * scale,
		width: 327 * scale
	},
	searchStyle: {
		width: 327 * scale,
		height: 36 * scale,
		backgroundColor: 'rgb(110,178,253)',
		borderRadius: 6 * scale,
		marginLeft: 0
	},
	searchLeftIconStyle: {
		marginLeft: 50 * scale,
		tintColor: '#fff',
	},
	headTab: {
		width: '100%',
		marginTop: 10 * scale,
		flexDirection: 'row',
		justifyContent: 'space-around',
		alignItems: 'center',
		marginBottom: 15 * scale
	},
	tabText: {
		color: '#fff',
		fontSize: 12 * scale,
		lineHeight: 30 * scale,
		textAlign: 'center',
		width: 55 * scale,
		fontWeight: 'bold',
		opacity: .6
	},
	tabTextActive: {
		opacity: 1
	},
	showBoxOut: {
		height: 72 * scale,
		width: '100%',
		flexDirection: 'row',
		justifyContent: 'center'
	},
	showBox: {
		width: 327 * scale,
		height: 72 * scale,
		borderRadius: 6 * scale,
		backgroundColor: style.color.white,
		flexDirection: 'row',
		justifyContent: 'space-around',
		alignItems: 'center'
	},
	tabActive: {
		borderBottomWidth: 2 * scale,
		borderStyle: 'solid',
		borderBottomColor: style.color.white
	},
	listBoxOut: {
		backgroundColor: '#F4F7FE',
		flex: 1
	},
	showBoxItem: {

	},
	showText: {
		marginTop: 5 * scale,
		color: style.color.atrous,
		fontSize: 12 * scale,
		fontWeight: 'bold',
	},
	showTitle: {
		color: '#848A96',
		fontSize: 12 * scale,
		fontWeight: 'bold',
	},
	timeTitle: {
		fontSize: 14 * scale,
		color: '#848A96',
		textAlign: 'right'
	},
	timeValue: {
		fontSize: 12 * scale,
		color: style.color.atrous,
		textAlign: 'right'
	},
	timeRight: {
		width: 150 * scale,
		justifyContent: 'flex-end',
		marginRight: 8 * scale
	},
	allBtn: {
		color: '#0E7FFD',
		fontWeight: 'bold',
		marginRight: 10 * scale
	},
	modelOut: { top: 230 * scale },
	modelOutDowm: { top: 140 * scale },
	timeIco: {
		width: 10 * scale,
		height: 20 * scale
	},
	dateSelect: {
		flexDirection: 'row',
		marginRight: 4 * scale
	},
})